<template>
  <div class="map-con">
    <baidu-map
      class="bm-view"
      :center="'上海'"
      :zoom="zoom"
      :scroll-wheel-zoom="true"
      @ready="handler"
    >
      <bm-panorama></bm-panorama>

      <div v-for="item in shops" :key="item._id">
        <bm-marker
          v-if="showShop"
          :position="{ lng: item.longitude, lat: item.latitude }"
          :dragging="true"
          @click="() => infoWindowOpen(item)"
        >
        </bm-marker>
      </div>
      <div v-for="item in users" :key="item.id">
        <bm-marker
          :position="item"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        >
          <bm-label
            :content="item.name"
            :labelStyle="{ color: 'red', fontSize: '12px' }"
            :offset="{ width: -4, height: 30 }"
          />
        </bm-marker>
      </div>
      <bm-info-window
        :show="show"
        :position="{ lng: curShop.longitude, lat: curShop.latitude }"
        @close="infoWindowClose"
        >{{ curShop.title }}</bm-info-window
      >
      <bm-info-window
        :show="showRes"
        :icon="img"
        :position="curRes.point"
        @close="showRes = false"
      >
        <div>
          {{ curRes.title }}
        </div>
        <div>地址: {{ curRes.address }}</div>
      </bm-info-window>
      <bm-local-search
        class="search-result"
        :keyword="keyword"
        :auto-viewport="true"
        location="上海"
        :panel="false"
        @markersset="resultshtmlset"
      ></bm-local-search>
      <!-- <div v-for="item in users" :key="item.id + '-1'">
        <bm-transit
          v-if="curShop.longitude"
          :start="item"
          :end="{ lng: curShop.longitude, lat: curShop.latitude }"
          :auto-viewport="true"
          location="上海"
          @searchcomplete="(result) => markersset(result, item)"
        ></bm-transit>
      </div> -->
    </baidu-map>
    <div class="search-con">
      <Input
        v-model="keyword"
        clearable
        placeholder="请输入关键字..."
        style="width: 200px"
        @on-change="handleChange"
      />
      <Button type="primary" style="margin-left: 10px">确定</Button>
      <Button type="primary" style="margin-left: 10px" @click="handleUpdate"
        >更新地址</Button
      >
      <Checkbox style="margin-left: 10px" v-model="showShop">查看店铺</Checkbox>
    </div>
    <div class="search-result" v-show="results.length">
      <div
        class="res-item"
        v-for="item in results"
        :key="item.uid"
        @click="handleResClick(item)"
      >
        <div class="title">{{ item.title }}</div>
        <div class="address">
          <span style="color: black">地址：</span>{{ item.address }}
        </div>
      </div>
    </div>

    <div class="table-con">
      <Table
        row-key="id"
        border
        :columns="columns"
        :data="tableData"
        height="600"
        @on-row-click="handleRowClick"
      ></Table>
    </div>

    <div class="detail-con" v-show="detailUrl">
      <iframe style="width: 100%; height: 100%" :src="detailUrl" />
    </div>
  </div>
</template>

<script>
import { commonApi } from "@/api";
import img from "./position.svg";
export default {
  data() {
    return {
      detailUrl: "",
      showShop: true,
      img,
      showRes: false,
      keyword: "",
      curRes: {
        point: {}
      },
      results: [],
      columns: [
        {
          title: "店铺名称",
          key: "title",
          width: 320,
          tree: true
        },
        {
          title: "评分",
          key: "avgscore"
        },
        {
          title: "人均消费",
          key: "avgprice"
        },
        {
          title: "用户名",
          key: "name"
        },
        {
          title: "距离",
          key: "disText"
        },
        {
          title: "时间",
          key: "timeText"
        },
        {
          title: "详情",
          key: "id",
          render: (h, params) => {
            console.log(params.row.id);
            return params.row.title ? (
              <Button
                type="text"
                on-click={() => {
                  window.open(
                    `https://www.meituan.com/xiuxianyule/${
                      params.row.id.split("-")[0]
                    }/`
                  );
                }}
              >
                详情
              </Button>
            ) : (
              ""
            );
          }
        }
      ],
      tableData: [],
      curShop: {},
      start: {
        lat: 31.2396,
        lng: 121.4815
      },
      end: {
        lat: 31.0382,
        lng: 121.2116
      },
      show: false,
      zoom: 11,
      shops: [],
      users: [],
      userMap: {},
      BMap: null,
      map: {},
      disList: [],
      shopMap: {}
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.main.userInfo;
    },
    userPoint() {
      const { lat, lng } = this.userInfo;
      return {
        lat,
        lng
      };
    }
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    handleRowClick(data) {
      if (data.title) {
        this.infoWindowOpen(data);
      }
    },
    getDisData() {
      commonApi({
        url: "/distance/getDisData",
        method: "get",
        data: {}
      }).then(async res => {
        this.disList = res.list;
        await this.getShops(res.ids);
        let obj = {};
        let ids = [];
        res.list.forEach((item, i) => {
          if (!obj[item.shopId]) {
            ids = [];
            obj[item.shopId] = {
              ...this.shopMap[item.shopId],
              children: []
            };
          }
          if (!ids.includes(item.userId)) {
            obj[item.shopId].children.push({
              ...item,
              ...this.userMap[item.userId],
              id: i
            });
            ids.push(item.userId);
          }
        });
        let list = [];
        for (let key in obj) {
          if (obj[key].id) {
            list.push({
              ...obj[key],
              id: key + "-" + obj[key].id
            });
          }
        }
        this.tableData = list;
        console.log(list);
      });
    },
    getShops(ids) {
      return commonApi({
        url: "/shop/find",
        method: "post",
        data: {
          query: {
            id: ids
          }
        }
      }).then(res => {
        this.shops = res.filter(item => item.avgscore > 4.5);
        this.shops.forEach(item => {
          this.shopMap[item.id] = item;
        });
        // this.setDisData();
      });
    },
    async setDisData() {
      for (let i = 0; i < this.shops.length; i++) {
        console.log(i);
        let data = await this.searchRoute(this.userInfo, this.shops[i]);
        if (data && data.timeNum) {
          await commonApi({
            url: "/distance",
            method: "post",
            data: {
              data: [data]
            }
          });
        }

        await this.sleep();
      }
    },
    async sleep() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, 1500);
      });
    },
    markersset(result, user) {
      console.log(result, user);
    },
    getUsers() {
      commonApi({
        url: "/user/getPlayer",
        method: "get",
        data: {}
      }).then(res => {
        res.forEach(item => {
          this.userMap[item.id] = item;
        });
        console.log(this.userMap);
        this.users = res;
        this.getDisData();
      });
    },
    handleChange({ value }) {
      if (!value) {
        this.results = [];
        this.showRes = false;
      }
    },
    handleResClick(res) {
      this.curRes = res;
      this.showRes = true;
      setTimeout(() => {
        this.curRes = res;
        this.showRes = true;
      }, 200);
    },
    resultshtmlset(arr) {
      console.log(arr);
      this.results = arr;
    },
    infoWindowClose() {
      this.show = false;
    },
    infoWindowOpen(item) {
      this.curShop = item;
      this.show = true;
      setTimeout(() => {
        this.curShop = item;
        this.show = true;
      }, 200);
      // let list = [];
      // this.users.forEach((user) => {
      //   list.push(this.searchRoute(user, this.curShop));
      // });
      // Promise.all(list).then((res) => {
      //   console.log(res);
      // });
    },
    handler({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      console.log(BMap, map);
    },
    handleUpdate() {
      commonApi({
        url: "/user/:id",
        method: "PUT",
        data: {
          id: this.userInfo.id,
          ...this.curRes.point
        }
      }).then(res => {
        this.$store.commit("userInfo", res);
        localStorage.setItem("userInfo", JSON.stringify(res));
        this.$Message.success("修改成功");
        this.showRes = false;
      });
    },
    searchRoute(user, shop) {
      return new Promise(resolve => {
        var transit = new this.BMap.TransitRoute(this.map, {
          renderOptions: { map: this.map },
          onSearchComplete: function(results) {
            let status = transit.getStatus();
            if (status != 0) {
              return;
            }
            var plan = results.getPlan(0);
            resolve({
              shopId: shop.id,
              userId: user.id,
              timeNum: plan.getDuration(false),
              timeText: plan.getDuration(true),
              disNum: plan.getDistance(false),
              disText: plan.getDistance(true)
            });
          }
        });
        var start = new this.BMap.Point(user.lng, user.lat);
        var end = new this.BMap.Point(shop.longitude, shop.latitude);
        transit.search(start, end);
        setTimeout(() => {
          resolve();
        }, 4000);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.map-con {
  width: 100%;
  height: 100%;
  position: relative;
  .detail-con {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }
  .bm-view {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .search-con {
    width: 500px;
    position: absolute;
    top: 30px;
    left: 50px;
  }
  .search-result {
    position: absolute;
    width: 300px;
    top: 70px;
    left: 50px;
    background: white;
    border: 1px solid;
    .res-item {
      border-bottom: 1px solid;
      cursor: pointer;
      padding: 5px;
      &:hover {
        background: rgb(228, 226, 226);
      }
      &:last-child {
        border: none;
      }
      .title {
        color: blue;
      }
      .address {
        color: #777777fc;
      }
    }
  }
  .table-con {
    position: absolute;
    width: 50%;
    height: 600px;
    bottom: 0;
    right: 0;
  }
}
</style>
